package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.User;
import com.stlm2.util.Convert;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.entity.Messages;
import com.stlm2.dems.dao.MessagesDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;

@Service("messagesService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class MessagesService extends BaseServiceImpl<Messages> {

	@Resource
	private MessagesDao messagesDao;
	@Resource
	private UserDao userDao;


	@Override
	protected BaseDao <Messages> getDao() {
		return messagesDao;
	}


	public List<ModelMap> convert(List<Messages> messagesList){
		List<ModelMap> list = new ArrayList<ModelMap>();
		if(messagesList != null && messagesList.size() > 0){
			for(Messages messages : messagesList){
				ModelMap map = buildModel(messages);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModel(Messages messages){
		ModelMap model = new ModelMap();
		if(messages!= null){
			model.put("id", messages.getId());
			model.put("ifRead", messages.getIfRead()!=null?messages.getIfRead():false);
			model.put("title", messages.getTitle()!=null ? messages.getTitle().trim() : "");
			model.put("content",messages.getContent()!= null ? messages.getContent().trim() : "");
			model.put("createTime", Convert.toFullYMDHMS(messages.getCreateTime()));
			model.put("readTime", messages.getReadTime()!=null?Convert.toFullYMDHMS(messages.getReadTime()):"");

		}
		return model;
	}

	public List<ModelMap> convertSimple(List<Messages> messagesList){
		List<ModelMap> list = new ArrayList<ModelMap>();
		if(messagesList != null && messagesList.size() > 0){
			for(Messages messages : messagesList){
				ModelMap map = buildModelSimple(messages);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModelSimple(Messages messages){
		ModelMap model = new ModelMap();
		if(messages!= null){
			model.put("id", messages.getId());
			model.put("ifRead", messages.getIfRead()!=null?messages.getIfRead():false);
			model.put("title", messages.getTitle()!=null ? messages.getTitle().trim() : "");
			model.put("content",messages.getContent()!= null ? messages.getContent().trim() : "");
			model.put("createTime", Convert.toShortYMD(messages.getCreateTime()));
		}
		return model;
	}
    //分页获取用户 消息
	public  String getUserMessages(String pageNo,String token){
		ModelMap model=new ModelMap();
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		int page=1;
		if(org.apache.commons.lang.math.NumberUtils.isDigits(pageNo)){
			page= org.apache.commons.lang.math.NumberUtils.toInt(pageNo);
		}
		Messages param= new Messages();
		param.setUserId(user.getId());
		PageView pageview = getPage(page, 20, param);
		if(pageview != null){
			model.put("messages", convertSimple(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
		}
		model.put("pageNo", page);
		return CodeContent.getModelByCode(1,"",model);
	}

	//获取未读消息个数
	public  String countNotReadMessages(String token){
		ModelMap model=new ModelMap();
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		int count=0;
		count=messagesDao.getNotRead(user.getId());
		model.put("count", count);
		return CodeContent.getModelByCode(1,"",model);
	}
    //获取用户单个消息
	public  String getOneMessages(String token,String messagesId){
		ModelMap model=new ModelMap();
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(StringUtils.isBlank(messagesId)||!org.apache.commons.lang.math.NumberUtils.isDigits(messagesId)){
			return CodeContent.getModelByCode(0,"请提供消息的id",null);
		}
		Messages messages=messagesDao.getById(org.apache.commons.lang.math.NumberUtils.toInt(messagesId));
		if(messages!=null){
			model.put("message",buildModelSimple(messages));
		}else {
			return CodeContent.getModelByCode(0,"此消息不存在",null);
		}
		return CodeContent.getModelByCode(1,"",model);
	}

    //修改未读消息为已读消息
	public  String updateNotReadMessages(String token,String messagesId){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(StringUtils.isBlank(messagesId)||!org.apache.commons.lang.math.NumberUtils.isDigits(messagesId)){
			return CodeContent.getModelByCode(0,"请提供修改消息的id",null);
		}
		Messages messages=messagesDao.getById(org.apache.commons.lang.math.NumberUtils.toInt(messagesId));
		messages.setIfRead(true);
		messages.setReadTime(new Date());
		messagesDao.modify(messages);
		return CodeContent.getModelByCode(1,"",null);
	}


    //商城首页 滚动消息
	public String rollMessage(String token){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		Boolean ifShow=false;
		String val=null;//做单营业额 或 红包金额
		String type=null;//order 或redPackets   做单或红包
		String unit="积分";
		String message="";
		String url="";
		Boolean bigRedPacket=false;
		Boolean virtualUser=false;//是否大红包
		ModelMap model=new ModelMap();
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			Long time=new Date().getTime();
			Set<String>keyList=jedis.keys("message*");
			List<String> stringList=new ArrayList<String>();
			if(keyList!=null&& keyList.size()>0){
				for (String key:keyList) {
					stringList.add(key);
				}
			}
			if(stringList!=null&&stringList.size()>0){
				Collections.sort(stringList);
				int index=stringList.size()-1;
				String key=null;
				String userKey=null;
				User user1=new User();// 领红包用户
				Long createTime=null;//创建时间
			    abc:for (int i=index;i>=0;i--){
					key=stringList.get(i);
					userKey="userMessage:"+user.getId()+":"+key;
					if(!"y".equals(jedis.get(userKey))){
						jedis.set(userKey,"y");
						jedis.expire(userKey,86400);
						val=jedis.get(key);
						if(key!=null&&val!=null){
							String [] keyStr=key.split(":");
							type=keyStr[3];
							createTime=NumberUtils.toLong(keyStr[1]);

								if(keyStr.length>=5){
									if("big".equals(keyStr[4])){
										bigRedPacket=true;
									}

								}
								if(NumberUtils.toInt(keyStr[2])>0){
									user1 = userDao.getById(NumberUtils.toInt(keyStr[2]));
									if (user1 != null) {

										break abc;
									}
								}else {
									virtualUser=true;
									break abc;
								}


						}

					}
				}

				if(type!=null&&val!=null&&createTime!=null){
				    ifShow=true;
				    Long refer=time-createTime;
				    Long second=refer/1000;
					if(type.equals("redPackets")){
						String userName="";
						if(virtualUser){//虚拟账号
							userName=virtualPhone();
						}else {
							userName=user1.getRealName();
							if(NumberUtils.isDigits(userName)){
								userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
							}
							if(user1.getAvotorr()!=null)
								url=user1.getAvotorr();
							System.out.println("userId"+user.getId()+"非虚拟用户===="+userName);
						}
						unit="红包积分";
						if(second<60L){
							message=userName+" "+second+"秒前在商城抢到";
						}else if(60L<=second && second<120L){
							message=userName+" 1分钟前在商城抢到";
						}else if(120L<=second && second<180L){
							message=userName+" 2分钟前在商城抢到";
						}else if(180L<=second && second<240L){
							message=userName+" 3分钟前在商城抢到";
						}else if(240L<=second && second<300L){
							message=userName+" 4分钟前在商城抢到";
						}else {
							message=userName+" 5分钟前在商城抢到";
						}
					}else if(type.equals("tixian")) {
						String userName=user1.getRealName();
						if(NumberUtils.isDigits(userName)){
							userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
						}
                        if(user1.getAvotorr()!=null)
                            url=user1.getAvotorr();
                        if(second<60L){
                            message=userName+" "+second+"秒前在商城兑换";
                        }else if(60L<=second && second<120L){
                            message=userName+" 1分钟前在商城兑换";
                        }else if(120L<=second && second<180L){
                            message=userName+" 2分钟前在商城兑换";
                        }else if(180L<=second && second<240L){
                            message=userName+" 3分钟前在商城兑换";
                        }else if(240L<=second && second<300L){
                            message=userName+" 4分钟前在商城兑换";
                        }else {
                            message=user1.getRealName()+" 5分钟前在商城兑换";
                        }
                    }else if(type.equals("tixianApply")){
						String userName=user1.getRealName();
						if(NumberUtils.isDigits(userName)){
							userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
						}
                        if(user1.getAvotorr()!=null)
                            url=user1.getAvotorr();
                        if(second<60L){
                            message=userName+" "+second+"秒前在商城申请兑换";
                        }else if(60L<=second && second<120L){
                            message=userName+" 1分钟前在商城申请兑换";
                        }else if(120L<=second && second<180L){
                            message=userName+" 2分钟前在商城申请兑换";
                        }else if(180L<=second && second<240L){
                            message=userName+" 3分钟前在商城申请兑换";
                        }else if(240L<=second && second<300L){
                            message=userName+" 4分钟前在商城申请兑换";
                        }else {
                            message=userName+" 5分钟前在商城申请兑换";
                        }
                    }else  if(type.equals("slyderAdventures")){
						String userName=user1.getRealName();
						unit="";
						if(NumberUtils.isDigits(userName)){
							userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
						}
						if(user1.getAvotorr()!=null)
							url=user1.getAvotorr();
						if(second<60L){
							message=userName+" "+second+"秒前在商城抽到";
						}else if(60L<=second && second<120L){
							message=userName+" 1分钟前在商城抽到";
						}else if(120L<=second && second<180L){
							message=userName+" 2分钟前在商城抽到";
						}else if(180L<=second && second<240L){
							message=userName+" 3分钟前在商城抽到";
						}else if(240L<=second && second<300L){
							message=userName+" 4分钟前在商城抽到";
						}else {
							message=userName+" 5分钟前在商城抽到";
						}
					}else{
						String userName=user1.getRealName();
						unit="元红包";
						if(NumberUtils.isDigits(userName)){
							userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
						}
						if(user1.getAvotorr()!=null)
							url=user1.getAvotorr();
						if(second<60L){
							message=userName+" "+second+"秒前在商城注册领取";
						}else if(60L<=second && second<120L){
							message=userName+" 1分钟前在商城注册领取";
						}else if(120L<=second && second<180L){
							message=userName+" 2分钟前在商城注册领取";
						}else if(180L<=second && second<240L){
							message=userName+" 3分钟前在商城注册领取";
						}else if(240L<=second && second<300L){
							message=userName+" 4分钟前在商城注册领取";
						}else {
							message=userName+" 5分钟前在商城注册领取";
						}
					}

				}

			}

		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}
		model.put("ifShow",ifShow);
		model.put("url",url);
		model.put("message",message);
		model.put("type",unit);
		model.put("value",val);
		model.put("bigRedPacket",bigRedPacket);
		return CodeContent.getModelByCode(1,"",model);

	}

	//商城大转盘滚动消息
	public String rollMessage2(ModelMap model){
		JedisPool pool = null;
		Jedis jedis = null;
		List<ModelMap> modelList = new ArrayList<ModelMap>();
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			Long time=new Date().getTime();
			Set<String>keyList=jedis.keys("slyderAdventuresMessage*");
			List<String> stringList=new ArrayList<String>();
			if(keyList!=null&& keyList.size()>0){
				for (String key:keyList) {
					stringList.add(key);
				}
			}
			if(stringList!=null&&stringList.size()>0){
				Collections.sort(stringList);
				for (int i =0 ;i <stringList.size() ;i++){
					if(modelList.size()<20){
						ModelMap model1=new ModelMap();
						StringBuffer message= new StringBuffer();
						String key = stringList.get(i);
						String [] keyStr=key.split(":");
						Long createTime =NumberUtils.toLong(keyStr[1]);
						String phone=keyStr[2];
						String jiangPinLevel=jedis.get(key);
						Long refer=time-createTime;
						Long second=refer/1000;
						if(second<60L){
							message.append(second + "秒前");
						}else if(60L<=second && second<120L){
							message.append( "1分钟前");
						}else if(120L<=second && second<180L){
							message.append( "2分钟前");
						}else if(180L<=second && second<240L){
							message.append( "3分钟前");
						}else if(240L<=second && second<300L){
							message.append( "4分钟前");
						}else {
							message.append( "5分钟前");
						}
						model1.put("phone",phone );
						model1.put("time", message.toString());
						model1.put("message","在商城抽到" );
						model1.put("jiangPinLevel", jiangPinLevel);
						modelList.add(model1);
					}else {
						break;
					}
				}
			}
			while (modelList.size()<20){
				ModelMap model1=new ModelMap();
				model1.put("phone",falsePhoneData() );
				model1.put("time", "5分钟前");
				model1.put("message", "在商城抽到");
				model1.put("jiangPinLevel", falseLevelData());
				modelList.add(model1);
			}
			model.put("data",modelList);
			model.put("code",1);
			model.put("msg","success");
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}
		return new JSONObject(model).toString();
	}
	//构造虚假大转盘虚假中奖手机号
	private String falsePhoneData(){
		StringBuffer phone=new StringBuffer();
		Random random = new Random();
		int num=random.nextInt(9);
		int num1=random.nextInt(9);
		int num2=random.nextInt(9);
		int num3=random.nextInt(9);		int num4=random.nextInt(9);
		phone.append("13");
		phone.append(num);
		phone.append("****");
		phone.append(num1);
		phone.append(num2);
		phone.append(num3);
		phone.append(num4);
		return phone.toString();
	}

	//构造虚拟大红包用户手机号
	private String virtualPhone(){
		StringBuffer phone=new StringBuffer();
		Random random = new Random();
		int num=random.nextInt(9);
		int num1=random.nextInt(9);int num2=random.nextInt(9);
		int num3=random.nextInt(9);int num4=random.nextInt(9);
		phone.append("15");
		phone.append(num);
		phone.append("****");
		phone.append(num1);
		phone.append(num2);
		phone.append(num3);
		phone.append(num4);
		return phone.toString();
	}
	//构造大转盘虚假中奖等级5-8等奖
	private String falseLevelData(){
		Random random = new Random();
		int num=random.nextInt(3)+5;
		return null;
	}


}